package com.lczyfz.campusinfo.modules.wechat.utils;


import com.alibaba.fastjson.JSON;
import com.lczyfz.campusinfo.modules.wechat.entity.AccessToken;
import com.lczyfz.campusinfo.modules.wechat.entity.WeChatBaseResult;

public class WeChatUtils {

    //测试号
  //   private static final String AppID = "wxf7d7d5aa1e14ad9d";
  //    private static final String AppSecret = "bf5fd2b81c260e1a0e98539c9e21bae6";

    private static final String AppID = "wxb56b1df8d42b57fb";
    private static final String AppSecret = "4bcae047f7fd559add369b94cb4438b2";
    public static String ACCESS_TOKEN = "0";

    //TODO:通过判断使用的当前时间与时效时间比较，实现懒更新
    public static void updateAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppID + "&secret=" + AppSecret;
        AccessToken accessToken = JSON.parseObject(HttpClientUtils.sendHttpGet(url), AccessToken.class);
        ACCESS_TOKEN = accessToken.getAccess_token();
    }

    //通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token（该access_token用于调用其他接口）不同。
    public static AccessToken getAuthorizationAccessTokenByCode(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppID + "&secret=" + AppSecret +
                "&code=" + code + "&grant_type=authorization_code";
        String result = HttpClientUtils.sendHttpGet(url);
        System.out.println("result = " + result);
        AccessToken accessToken = JSON.parseObject(result, AccessToken.class);
        System.out.println("accessToken = " + accessToken);

        return accessToken;
    }

    public static Boolean checkErrcode(WeChatBaseResult weChatBaseResult) {
        Boolean result = false;
        switch (weChatBaseResult.getErrcode()) {
            case 0: {
                result = true;
                break;
            }
            case 40001: {
                updateAccessToken();
                break;
            }
            case 40014: {
                updateAccessToken();
                break;
            }
            case 41001: {
                updateAccessToken();
                break;
            }
            case 42001: {
                updateAccessToken();
                break;
            }

        }

        return result;
    }
}
